import { record } from 'rrweb';

const BUFFER_DURATION = 30000;
const CHUNK_SIZE = 5000;
let activeBuffer = 'A';
let buffers = {
  A: [],
  B: [],
};
let currentChunk = [];
let lastChunkTime = 0;

// 使用TextEncoder进行二进制编码
const textEncoder = new TextEncoder();

function startRecording() {
  let events = [];

  record({
    emit(event) {
      events.push(event);

      const now = performance.now();
      if (now - lastChunkTime >= CHUNK_SIZE) {
        storeEventChunk(events);
        events = [];
        lastChunkTime = now;
      }
    },
    // 保持原有配置...
  });
}

function storeEventChunk(events) {
  const serialized = JSON.stringify(events);
  const encoded = textEncoder.encode(serialized);

  // 添加到当前缓冲区
  currentChunk.push(encoded);

  // 缓冲区管理
  if (currentChunk.length * CHUNK_SIZE > BUFFER_DURATION) {
    buffers[activeBuffer] = [...currentChunk];
    currentChunk = [];
  }
}

function handleBufferSwitch(bufferName) {
  buffers[activeBuffer] = [...currentChunk];
  currentChunk = [];
  activeBuffer = bufferName;
  buffers[bufferName === 'A' ? 'B' : 'A'] = [];
}

function sendRecordingData() {
  // 合并所有数据块
  const allEvents = [];
  buffers[activeBuffer].forEach((chunk) => {
    const decoder = new TextDecoder();
    const jsonStr = decoder.decode(chunk);
    allEvents.push(...JSON.parse(jsonStr));
  });

  // 使用Transferable对象提高传输效率
  const response = {
    type: 'RECORDING_DATA',
    events: allEvents,
  };

  // 查找所有ArrayBuffer用于传输
  const transferables = [];
  buffers[activeBuffer].forEach((chunk) => {
    if (chunk.buffer instanceof ArrayBuffer) {
      transferables.push(chunk.buffer);
    }
  });

  self.postMessage(response, transferables);
}

self.addEventListener('message', ({ data }) => {
  switch (data.type) {
    case 'INIT':
      startRecording();
      break;
    case 'SWITCH_BUFFER':
      handleBufferSwitch(data.bufferName);
      break;
    case 'REQUEST_DATA':
      sendRecordingData();
      break;
  }
});
